package com.fansl.koala.quickdev.component.message.email.service.impl;

import com.fansl.koala.quickdev.common.bean.entity.SendMailMessage;
import com.fansl.koala.quickdev.component.message.email.service.MailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

/**
 * @author fansl
 * @Description: email发送服务实现类
 * @date 2020/3/18 17:35
 */
@Component
public class MailServiceImpl implements MailService {
    @Resource
    private JavaMailSenderImpl javaMailSender;
    @Value("${spring.mail.username}")
    private String sender;

    /**
     * 发送基本邮件
     *
     * @param mailMessage 邮箱消息
     * @return 返回结果
     * @throws Exception 异常信息
     */
    @Override
    public Object sendMimeMail(SendMailMessage mailMessage) throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);

        //设置邮件标题
        messageHelper.setSubject(mailMessage.getSubject());
        //设置邮件正文
        messageHelper.setText(mailMessage.getContent(),true);
        //设置收件人
        messageHelper.setTo(mailMessage.getReceiver());
        //设置发件人
        messageHelper.setFrom(sender);
        //发送邮件
        javaMailSender.send(messageHelper.getMimeMessage());

        return mailMessage.getReturnContent();
    }

    /**
     * 发送简单消息
     *
     * @param mailMessage 邮箱消息
     * @return 返回结果
     * @throws Exception 异常消息
     */
    @Override
    public Object sendSimpleMail(SendMailMessage mailMessage) throws Exception {
        SimpleMailMessage message = new SimpleMailMessage();
        //设置邮件标题
        message.setSubject(mailMessage.getSubject());
        //设置邮件正文
        message.setText(mailMessage.getContent());
        //设置收件人
        message.setTo(mailMessage.getReceiver());
        //设置发件人
        message.setFrom(sender);
        //发送邮件
        javaMailSender.send(message);

        return mailMessage.getReturnContent();
    }
}
